package com.qidianit.task.service.impl;

import com.qidianit.task.mapper.TaskMapper;
import com.qidianit.task.pojo.Task;
import com.qidianit.task.service.TaskService;
import com.qidianit.task.util.pojo.QdResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Author hitsune
 * @Company kafu chino
 * @Description
 * @Time 2024/9/10 17:00
 */

@Service
public class TaskServiceImpl implements TaskService {
    @Autowired
    private TaskMapper taskMapper;

    @Override
    public QdResult list(String projectId, Long parentId) {
        return QdResult.success(taskMapper.selectList(projectId, parentId));
    }

    @Override
    public QdResult selectById(Long taskId) {
        return QdResult.success(taskMapper.selectById(taskId));
    }

    @Override
    public QdResult saveTask(Task task) {
        task.setTaskStatus(1);
        task.setTaskParent(2);
        task.setCreateTime(new Date());
        int i = taskMapper.insertTask(task);//突然明白之前为什么insertTask是int类型的了
        if (i == 1 && !task.getTaskParentId().equals(new Long(0))){
            //如果要插入的taskParentId为0则是父节点
            Task parentTask = taskMapper.selectById(task.getTaskParentId());//查询父节点任务
            if (parentTask.getTaskParent().equals(new Integer(2))){//判断父级任务的parent是否是1
                parentTask.setTaskParent(1);
                taskMapper.updateById(parentTask);
            }
        }
        return i == i?QdResult.success(task) : QdResult.error();
    }

    @Override
    public void replaceTask(Task task) {
         taskMapper.replaceById(task);
    }

    @Override
    public void deleteByTaskId(Long taskId) {
        boolean isMoreThanTow = false;
        //通过送入的taskId来查询对应的taskParentId
        Long taskParentId = taskMapper.selectById(taskId).getTaskParentId();
        //如果taskParentId的和大于1，那么意味着这个父节点有其他子节点
        //如果taskParentId为0，证明这已经是顶层父节点，没有子节点了，可以直接删除，不做修改
        if (taskParentId != 0) {
            if (taskMapper.getTaskParentId(taskParentId) >= 2) {
                isMoreThanTow = false;
            } else {
                isMoreThanTow = true;
            }
            if (isMoreThanTow) {
                //将这个父节点的taskParent修改为2
                taskMapper.changeTaskParent(taskParentId);
            }
        }
        //利用taskId将状态改为99
        taskMapper.deleteByTaskId(taskId);
    }
}
